#include "OptionParser.h"
#include <QDebug>

OptionParser::OptionParser(const QStringList &argList)
    : action(HELP)
{
    initSynonims();

    OPTION_TYPE option;
    for (int i = 1; i < argList.size(); ++i) {
        const QString &arg = argList.at(i);
        if (i == 1) {
            if (isOption(INSERT, arg, Qt::CaseInsensitive)) {
                action = INSERT;
            } else if (isOption(MODIFY, arg, Qt::CaseInsensitive)) {
                action = MODIFY;
            } else if (isOption(REMOVE, arg, Qt::CaseInsensitive)) {
                action = REMOVE;
            } else {
                qDebug() << "fail on operation parse!";
                action = HELP;
                break;
            }
            continue;
        }
        switch (action) {
            case INSERT: {
                if (isOption(FORMAT, arg)) {
                    option = FORMAT;
                } else if (isOption(OCCUR, arg)) {
                    option = OCCUR;
                } else if (isOption(NAME, arg)) {
                    option = NAME;
                } else {
                    parseSubOptions(option, arg);
                }
                break;
            }
            case MODIFY: {
                break;
            }
            case REMOVE: {
                break;
            }
            default: {
                qDebug() << "HELP!";
                break;
            }
        }
    }
}

void OptionParser::initSynonims()
{
    options.insert(HELP,   Option(QStringList() << "help" << "-help" << "--help" << "-h"));
    options.insert(INSERT, Option(QStringList() << "insert" << "append" << "add"));
    options.insert(MODIFY, Option(QStringList() << "update" << "modify" << "edit"));
    options.insert(REMOVE, Option(QStringList() << "delete" << "remove" << "drop"));
    options.insert(FORMAT, Option(QStringList() << "-format" << "-f"));
    options.insert(OCCUR,  Option(QStringList() << "-occur"  << "-o"));
    options.insert(NAME,   Option(QStringList() << "-name"   << "-n"));
}

void OptionParser::parseSubOptions(OPTION_TYPE optionType, const QString &arg)
{
    Option option = options.value(optionType);
    option.value = arg;
    options.remove(optionType);
    options.insert(optionType, option);
}

bool OptionParser::isOption(OPTION_TYPE type, const QString &arg, Qt::CaseSensitivity sens)
{
    return options.value(type).synonims.contains(arg, sens);
}

QString OptionParser::value(OPTION_TYPE option)
{
    return options.value(option).value;
}
